package cn.shyouchi.wuguanjia.android.ui.home.security.thread.application;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.base.BaseFragment;
import cn.shyouchi.wuguanjia.android.event.ModuleChangeEvent;
import cn.shyouchi.wuguanjia.android.ui.home.security.thread.main.HomeModule;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import io.realm.Realm;
import io.realm.RealmResults;

import static cn.shyouchi.wuguanjia.android.R.id.topBar;

/**
 * A simple {@link Fragment} subclass.
 */
public class ApplicationFragment extends BaseFragment implements MenuItem.OnMenuItemClickListener, AppAdapter.ItemActionListener {


    @BindView(topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_index_app)
    RecyclerView mRvIndexApp;
    @BindView(R.id.rv_other_app)
    RecyclerView mRvOtherApp;

    MenuItem mMenuItem;
    MenuItem mQueryMenuItem;

    //    List<HomeModule> mModules = new ArrayList<>();
    List<HomeModule> mIndexModules = new ArrayList<>();
    List<HomeModule> mOtherModules = new ArrayList<>();

    AppAdapter mIndexAppAdapter;
    AppAdapter mOtherAppAdapter;
    @BindView(R.id.tv_drag_hint)
    TextView mTvDragHint;


    private ItemTouchHelper mItemTouchHelper;
    private ItemDragAndSwipeCallback mItemDragAndSwipeCallback;


    public ApplicationFragment() {

    }


    @Override
    public void initInjector() {

    }

    @Override
    public int initContentView() {
        return R.layout.fragment_application;
    }

    @Override
    public void getBundle(Bundle bundle) {

    }

    @Override
    public void initUI(View view) {

        ButterKnife.bind(this, view);
        mTopBar.setTitle("应用");
        showContent(false);

        mMenuItem = mTopBar.getToolbar().getMenu().add("编辑");
        mMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        mMenuItem.setOnMenuItemClickListener(this);


//        mQueryMenuItem = mTopBar.getToolbar().getMenu().add("查询");
//        mQueryMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
//        mQueryMenuItem.setOnMenuItemClickListener(this);


        mIndexAppAdapter = new AppAdapter(mIndexModules, this);

        mOtherAppAdapter = new AppAdapter(mOtherModules, this);


        mRvIndexApp.setItemAnimator(new DefaultItemAnimator());

        mRvIndexApp.setAdapter(mIndexAppAdapter);
        mRvIndexApp.setLayoutManager(new GridLayoutManager(getContext(), 4));

        mRvOtherApp.setAdapter(mOtherAppAdapter);
        mRvOtherApp.setLayoutManager(new GridLayoutManager(getContext(), 4));


        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder holder, int i) {
                LogUtil.e("Drag Start");
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder holder, int i, RecyclerView.ViewHolder viewHolder1, int i1) {
                LogUtil.e("Drag Move");
            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder holder, int i) {
                LogUtil.e("Drag End");
                EventBus.getDefault().post(new ModuleChangeEvent());
            }
        };


        mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mIndexAppAdapter);
        mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(mRvIndexApp);


        mIndexAppAdapter.setOnItemDragListener(listener);

        queryIndex();


    }

    @Override
    public void initData() {

    }


//    private void saveModule() {
//
//        mModules.add(new HomeModule(AttendanceActivity.class, R.mipmap.ic_home_module_sign, "考勤", false, 0, true));
//        mModules.add(new HomeModule(SignStatisticManagerActivity.class, R.mipmap.ic_home_module_stati, "考勤统计", false, 1, true));
//        mModules.add(new HomeModule(PatrolActivity.class, R.mipmap.ic_home_module_polling, "巡检", false, 2, true));
//        mModules.add(new HomeModule(PatrolStatisticManageActivity.class, R.mipmap.ic_home_module_polling_stati, "巡检统计", false, 3, true));
//        mModules.add(new HomeModule(PatrolStatisticManageActivity.class, R.mipmap.ic_home_module__form_up, "表单上传", false, 4, true));
//        mModules.add(new HomeModule(PatrolStatisticManageActivity.class, R.mipmap.ic_home_module_visitor, "访客通行", false, 5, true));
//        mModules.add(new HomeModule(MeetMainActivity.class, R.mipmap.ic_home_module_meeting, "会议", false, 6, true));
//        mModules.add(new HomeModule(EventManagerActivity.class, R.mipmap.ic_home_module_event_info, "项目设置", false, 7, true));
//
//
//        mModules.add(new HomeModule(EventManagerActivity.class, R.mipmap.ic_home_module_fix, "维修", false, 10));
//        mModules.add(new HomeModule(EventManagerActivity.class, R.mipmap.ic_home_module_train, "培训", false, 11));
//        mModules.add(new HomeModule(EventManagerActivity.class, R.mipmap.ic_home_module_workshow, "工作秀", false, 12));
//        mModules.add(new HomeModule(EventManagerActivity.class, R.mipmap.ic_home_module_report, "报岗", false, 13));
//        mModules.add(new HomeModule(EventManagerActivity.class, R.mipmap.ic_home_module_reportstatistic, "报岗统计", false, 14));
//
//
//        Realm realm = Realm.getDefaultInstance();
//        realm.beginTransaction();
//        realm.insertOrUpdate(mModules);
//        realm.commitTransaction();
//    }

    private void queryIndex() {
        mIndexModules.clear();
        mOtherModules.clear();

        Realm realm = Realm.getDefaultInstance();
        RealmResults<HomeModule> results = realm.where(HomeModule.class).findAllSorted("index");

        for (HomeModule m : results) {
            if (m.isShow()) {
                mIndexModules.add(m);
            } else {
                mOtherModules.add(m);
            }
        }

        mOtherAppAdapter.notifyDataSetChanged();
        mIndexAppAdapter.notifyDataSetChanged();
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item == mQueryMenuItem) {

//            saveModule();


        } else {
            if (item.getTitle().equals("编辑")) {
                item.setTitle("完成");
                mTvDragHint.setText("长按拖动可排序");
                mIndexAppAdapter.enableDragItem(mItemTouchHelper);
                mIndexAppAdapter.startEditMode();
                mOtherAppAdapter.startEditMode();

            } else {
                item.setTitle("编辑");
                mTvDragHint.setText("");
                mIndexAppAdapter.disableDragItem();
                mIndexAppAdapter.stopEditMode();
                mOtherAppAdapter.stopEditMode();
            }
        }
        return true;
    }

    @Override
    public void onItemAdd(View itemView, final HomeModule module, final int position) {


        if (mIndexAppAdapter.getData().size() < 8) {
            Realm realm = Realm.getDefaultInstance();
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    module.setShow(true);
                    mIndexModules.add(module);
                    mOtherModules.remove(module);
                    EventBus.getDefault().post(new ModuleChangeEvent());
                    mOtherAppAdapter.notifyDataSetChanged();
                    mIndexAppAdapter.notifyDataSetChanged();
                }
            });
        } else {
            ToastUtil.showToast("首页最多只能摆放8个模块");
        }


    }

    @Override
    public void onItemRemove(View itemView, final HomeModule module, int position) {
        Realm realm = Realm.getDefaultInstance();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                module.setShow(false);
                mOtherModules.add(0, module);
                mIndexModules.remove(module);
                EventBus.getDefault().post(new ModuleChangeEvent());
                mOtherAppAdapter.notifyDataSetChanged();
                mIndexAppAdapter.notifyDataSetChanged();
            }
        });
    }
}
